package com.lee.boot.head.first.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * @Auther: Lee
 * @Date: 2018/6/27 17:52
 * @Description:
 */
@Controller
@RequestMapping(value = "/file")
public class FileUpLoadDemo {
    @RequestMapping(value = "/uploadPage")
    public String uploadPage(){
        return "FileUPLoad";
    }

    @RequestMapping(value = "/upload")
    public String fileUp(HttpServletRequest request,MultipartFile file){
        String filename = file.getOriginalFilename();
        String clientfile = request.getSession().getServletContext().getRealPath("/")+ "upload/";
        File file2 = new File(clientfile);
//        如果目录不存在 创建目录
        if (!file2.exists()){
            file2.mkdir();
        }
        File file1 = new File(clientfile + filename);
        try {
            file.transferTo(file1);
        } catch (IOException e) {
            e.printStackTrace();
            return "index";
        }

        return "index";
    }
}
